﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace SharpHomeEngine
{
    public class Tag
    {
        private string MyName = "";
        protected object MyValue = null;

        public String Name { get{ return MyName; } }

        public virtual object ValueObj { get { return MyValue; } }

        public readonly DeviceInterface DeviceInterface;
        public readonly Device Device;

        public String Address 
        { 
            get 
            {
                return GetTagAddress(DeviceInterface, Device, this);
            } 
        }

        public Tag(DeviceInterface DeviceInterface, Device Device, String Name)
        {
            if (DeviceInterface == null)
            {
                throw new Exception("Device Interface cannot be null");
            }
            if (Device == null)
            {
                throw new Exception("Device cannot be null");
            }
            CheckName(Name);
            this.DeviceInterface = DeviceInterface;
            this.Device = Device;
            MyName = Name;
        }

        internal void SetValue(object Value)
        {
            MyValue = Value;
        }

        public static string GetTagAddress(DeviceInterface DeviceInterface, Device Device, Tag Tag)
        {
            return GetTagAddress(DeviceInterface.Name, Device.Name, Tag.Name);
        }

        public static string GetTagAddress(String DeviceInterface, String Device, String Tag)
        {
            return DeviceInterface + "." + Device + "." + Tag;
        }

        private void CheckName(String Name)
        {
            if (Name == null)
            {
                throw new Exception("Name cannot be null");
            }
            if (Name.Length == 0)
            {
                throw new Exception("Name cannot be empty");
            }
            Regex X = new Regex(@"^[\w]*$");
            if (!X.IsMatch(Name))
            {
                throw new Exception("A tag name can only consist of letters, numbers, and the underscore character!");
            }
        }

    }
}
